package com.cat.chapter036;

/**
 * @author cat
 * @description https://leetcode.cn/problems/serialize-and-deserialize-binary-tree/
 * @create 2025/6/17 21:50
 * @since JDK17
 */

public class Codec02 {
    final static int MAXN = 10001;
    TreeNode[] q = new TreeNode[MAXN];
    int l, r, cnt;
    StringBuilder sb = new StringBuilder();
    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        if (root == null) {
            return "";
        }
        f(root);
        return sb.toString();
    }
    public void f(TreeNode root) {
        l = r = 0;
        q[r++] = root;
        while (l < r) {
            int j = r;
            while (l < j) {
                TreeNode node = q[l++];
                sb.append(node.val + ",");
                if (node.left != null) {
                    q[r++] = node.left;
                } else {
                    sb.append("#,");
                }
                if (node.right != null) {
                    q[r++] = node.right;
                } else {
                    sb.append("#,");
                }
            }
        }
    }


    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        g(data.split(","));

        return null;
    }

    public TreeNode g(String[] vals) {
        l = r = cnt = 0;
        q[r++] = new TreeNode(Integer.valueOf(vals[cnt++]));
        while (l < r) {
            int j = r;
            while (l < j) {
                TreeNode node = q[l++];
                if (vals[cnt + 1].equals("#")) {
                    node.left = null;
                } else {
                    node.left = new TreeNode(Integer.valueOf(vals[cnt + 1]));
                    q[r++] = node.left;
                }
                if (vals[cnt + 2].equals("#")) {
                    node.right = null;
                } else {
                    node.right = new TreeNode(Integer.valueOf(vals[cnt + 2]));
                    q[r++] = node.right;
                }
                cnt += 2;
            }
        }
        return q[0];
    }

}
